package com.im.business.history.config;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Created leijun
 * @Date 2021/10/29 9:12 下午
 */
public class ComplexDatabaseShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {


    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> shardingValue) {
        Map<String, Collection<Long>> shardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        Collection<Long> groupIds = shardingValuesMap.get("group_id");
        Collection<Long> senderIds = shardingValuesMap.get("sender_id");
        List<String> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupIds) && !groupIds.contains(-1L)) {
            for (Long groupId : groupIds) {
                result.add(shardingValue.getLogicTableName() + (groupId % 2));
            }
        } else {
            for (Long senderId : senderIds) {
                result.add("im" + (senderId % 2));
            }
        }
        return result;
    }
}
